package cn.edu.whu.forecast.interceptor;

import cn.edu.whu.forecast.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置响应编码为UTF-8
        response.setCharacterEncoding("UTF-8");
        //获取 header里的token
        String token = request.getHeader("token");
        // 跨域请求options 返回为空
        String str = "OPTIONS";
        if (str.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }// 除了options跨域请求，都进入到jwt校验
        else {
            if (token == null) {
                response.getWriter().write("没有token！");
                response.setStatus(403);
                return false;
            }
            // 校验接口传进来的token信息
            boolean b = JwtUtil.checkToken(token);
            if (!b) {
                response.getWriter().write("签名验签失败 !");
                response.setStatus(403);
                return false;
            }
            return true;
        }
    }
}
